package cr

import (
	"context"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/apms"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/asserts"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/auths"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/beans"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/gins/middleware"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/loggers"
	"gitee.com/shiqiyue/xd-bi/internal/modules/cr/restful"
	"gitee.com/shiqiyue/xd-bi/internal/pkg/instance"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/rs/cors"
	ginCors "github.com/rs/cors/wrapper/gin"
	"go.uber.org/zap"
	"net"
	"time"
)

// 初始化rest
func RestfulInit(ctx context.Context, errCh chan error) {
	config := instance.GetConfig()
	httpAddress := config.Restful.Address
	httpListener, err := net.Listen("tcp", httpAddress)
	asserts.Nil(err, err)
	// gin设置
	gin.SetMode(gin.ReleaseMode)
	router := gin.Default()
	// 跨域配置
	corsOptions := cors.Options{AllowedOrigins: config.Restful.Cors.AllowedOrigins, AllowedHeaders: config.Restful.Cors.AllowedHeaders}
	// 设置通用中间件
	router.Use(loggers.RecoveryWithZap(true))
	router.Use(apms.OpenTracingMiddleware(instance.GetAppName()))
	router.Use(auths.RbacAuthMiddle(instance.GetAuthViper()))
	router.Use(middleware.GinContextToContextMiddleware())
	router.Use(loggers.Ginzap(time.RFC3339, true))
	router.Use(ginCors.New(corsOptions))

	// json反序列化设置
	binding.EnableDecoderUseNumber = true

	// 注册路由
	restRouterRegister(ctx, router)
	// http启动
	go func() {
		loggers.Info("restful启动", ctx, zap.String("监听地址", httpAddress))
		errCh <- router.RunListener(httpListener)
	}()
}

func restRouterRegister(ctx context.Context, router *gin.Engine) {
	// 初始化 handler
	handlers := &restful.Handlers{}
	err := beans.ProvideBean(handlers)
	asserts.Nil(err, err)
	err = beans.Populate()
	asserts.Nil(err, err)

	// 查询报表信息
	router.GET("bi/public/:code", handlers.GetReport)
	// 执行报表
	router.POST("bi/public/:code", handlers.ExecReport)
	// 获取字典
	router.POST("bi/dict/listByCode", handlers.GetDicts)
	// 获取区域
	router.GET("bi/dict/area", handlers.GetArea)

}
